import render_content from "./render_content.mjs";
import {
  nearest_data,
  nearest_datacontainer,
  nearest_formview,
  nearest_render,
} from "./nearest.mjs";
import datarover from "./datarover.mjs";
import collectdata from "./collectdata.mjs";

import { clearafterqueue } from "./delay_render.mjs";

export default function (element, template) {
  // if (template.data) {
  //   element.thin_data = template.data;
  // }
  if (template.name !== undefined) {
    element.setAttribute("name", template.name);
  }
  if (template.id !== undefined) {
    element.setAttribute("id", template.id);
  }
  if (template.class !== undefined) {
    let _class;
    if (typeof template.class === "function") {
      _class = template.class(element, template, nearest_data());
      // element.classList.add(template.class(element, template, nearest_data()));
    } else {
      // element.classList.add(template.class);
      _class = template.class;
    }
    _class?.split(" ").forEach((c) => {
      element.classList.add(c);
    });
  }
  if (template.width) {
    element.style.setProperty(
      "width",
      typeof template.width === "number"
        ? template.width + "px"
        : template.width
    );
  }
  if (template.height) {
    element.style.setProperty(
      "height",
      typeof template.height === "number"
        ? template.height + "px"
        : template.height
    );
  }

  if (template.type) {
    element.setAttribute("type", template.type);
  }

  //a 设置节点attribute
  let attr;
  if (element.nodeName === "A") {
    attr = template.attr;
  } else {
    attr = template.a;
  }
  if (attr) {
    Object.keys(attr).forEach(function (key) {
      if (typeof attr[key] === "function") {
        //var data_container = nearest_datacontainer(element);
        element.setAttribute(
          key,
          attr[key]({
            container: element,
            data: nearest_data(element),
          })
        );
      } else {
        if (attr[key]) element.setAttribute(key, attr[key]);
      }
    });
  }
  //style 设置节点样式
  if (template.style) {
    Object.keys(template.style).forEach(function (key) {
      if (typeof template.style[key] === "function") {
        //var data_container = nearest_datacontainer(element);
        element.style.setProperty(
          key,
          template.style[key]({
            container: element,
            data: nearest_data(element),
          })
        );
      } else {
        element.style.setProperty(key, template.style[key]);
      }
    });
  }

  //
  // 双向数据绑定
  //
  if (template.bind) {
    let value = datarover(element, template.bind);

    switch (element.nodeName.toLowerCase()) {
      case "input":
        if (element.getAttribute("type") === "checkbox") {
          element.checked = value;
        } else {
          element.value = value || "";
        }
        break;
      case "select":
      case "textarea":
        element.value = value || "";
        // console.log(element.value);
        // console.log({ ev: element.value, value });
        break;
      default:
        element.innerText = value || "";
        break;
    }

    element.addEventListener("change", (ev) => {
      // console.log({ bind: ev, value: element.value });
      if (
        element.nodeName.toLowerCase() === "input" &&
        element.getAttribute("type") === "checkbox"
      ) {
        datarover(element, template.bind, element.checked);
      } else {
        datarover(element, template.bind, element.value?.trim());
      }

      // thin.clearafterqueue();
      clearafterqueue();
    });

    if (template.afterbind) template.afterbind(element);
  } else {
    // 处理单向取值
    if (template.value) {
      element.value = render_content(element, template.value);
    }
  }

  //
  // 绑定event
  //
  if (template.event) {
    for (let key in template.event) {
      element.addEventListener(
        key,
        (ev) => {
          template.event[key]({
            sender: element,
            org_data: nearest_data(element),
            new_data: collectdata(nearest_datacontainer(element)),
            event: ev,
          });
        },
        false
      );
    }
  }

  //
  // 绑定click事件
  //
  if (template.click) {
    element.addEventListener(
      "click",
      function (e) {
        // 禁用

        // 搜集数据
        let datacontainer = nearest_datacontainer(this);
        let new_data = collectdata(datacontainer);
        // console.log({ this: this, datacontainer });

        let para = {
          sender: this,
          org_data: nearest_data(this),
          new_data: new_data,
          rowindex: datacontainer ? datacontainer.thin_rowindex : 0,
          event: e,
        };

        switch (element.nodeName) {
          case "BUTTON":
            element.disabled = true;
            para.done = function () {
              element.disabled = false;
            };
            break;
          default:
            break;
        }

        let tb = this.closest("tbody");
        if (tb?.thin_data) para.group_data = tb.thin_data;

        // 构造回调函数
        let formview = nearest_formview(this);

        if (formview) {
          para.editmode = function () {
            formview.thin_viewmode = "edit";
            formview.thin_render();
          };
          para.readmode = function () {
            formview.thin_viewmode = "read";
            formview.thin_render();
          };
        }

        // console.log({ this: this, element });

        para.rerender = function () {
          nearest_render(element).thin_render();
        };

        template.click(para);
      },
      false
    );
  }
}
